using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace InventorySystem
{
    public class GameItem : MonoBehaviour
    {
        [SerializeField]
        private ItemStack _stack;

        [SerializeField]
        private SpriteRenderer _spriteRenderer;

        [Header("扔物品设置")]
        [SerializeField]
        private float _colliderEnabledAfter = 1f;
        [SerializeField]
        private float _throwGravity = 2f;
        [SerializeField]
        private float _minThrowXForce = 3f;
        [SerializeField]
        private float _maxThrowXForce = 5f;
        [SerializeField]
        private float _throwYForce = 5f;

        private Collider2D _collider;
        private Rigidbody2D _rb;

        public ItemStack Stack => _stack;


        private void Awake()
        {
            _rb = GetComponent<Rigidbody2D>();
            _collider = GetComponent<Collider2D>();
            _collider.enabled = false;
        }

        private void Start()
        {
            SetupGameObject();
            StartCoroutine(EnableCollider(_colliderEnabledAfter));
        }

        private void OnValidate()
        {
            SetupGameObject();
        }

        private void SetupGameObject() 
        {
            if (_stack.Item == null) return;
            SetGameObject();
            AdjustNumberOfItems();
            UpdataGameObjectName();

        }

        private void SetGameObject() 
        {
            _spriteRenderer.sprite = _stack.Item.InGameSprite;
        }

        private void UpdataGameObjectName() 
        {
            var name = _stack.Item.Name;
            var number = _stack.IsStackable ? _stack.NumberOfItems.ToString() : "ns";
            gameObject.name = $"{name} ({number})";
        }

        private void AdjustNumberOfItems() 
        {
            _stack.NumberOfItems = _stack.NumberOfItems;
        }

        public ItemStack Pick() 
        {
            Destroy(gameObject);
            return _stack;
        }

        public void Throw(float xDir) 
        {
            
            var throwXForce = Random.Range(_minThrowXForce,_maxThrowXForce);
            _rb.velocity = new Vector2(Mathf.Sign(xDir) * throwXForce,_throwYForce);
            StartCoroutine(DisabeleGravity(_throwYForce));
        }

        private IEnumerator DisabeleGravity(float atVelocity) 
        {
            yield return new WaitUntil(() => _rb.velocity.y < -atVelocity);
            _rb.velocity = Vector2.zero;
            
        }

        private IEnumerator EnableCollider(float afterTime)
        {
            yield return new WaitForSeconds(afterTime);
            _collider.enabled = true;
        }

        public void SetStack(ItemStack itemStack) 
        {
            _stack = itemStack;
        }

    }
}